package android.pot.com.smartcar;

import android.app.Activity;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.pot.com.smartcar.base.BaseFragmentActivity;
import android.pot.com.smartcar.base.CommonListner;
import android.pot.com.smartcar.base.TabItem;
import android.pot.com.smartcar.config.MyConfig;
import android.pot.com.smartcar.entity.UserInfo;
import android.pot.com.smartcar.tool.LoginTool;
import android.pot.com.smartcar.ui.find.FindFragment;
import android.pot.com.smartcar.ui.home.HomesFragment;
import android.pot.com.smartcar.ui.login.LoginsActivity;
import android.pot.com.smartcar.ui.my.MyFragment;
import android.pot.com.smartcar.util.DensityUtils;
import android.pot.com.smartcar.util.ImageLoadUtils;
import android.pot.com.smartcar.util.OSUtils;
import android.pot.com.smartcar.util.PermissionUtil;
import android.pot.com.smartcar.util.UpdateManagers;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends BaseFragmentActivity implements View.OnClickListener, EasyPermissions.PermissionCallbacks {

    private TextView tv_home,  tv_area, tv_mine;

    private ImageView img_home,  img_area, img_mine;

    private final int WRITE_EXTERNAL_STORAGE_REQUEST_CODE = 200;

    private ImageView iv_point;

    private UpdateManagers updateM;

    private int curItem = 0;

    private Animation scale_to_normal;

    private final static int MIUI = 0;

    private final static int FLYME = 1;

    private final static int COMMON = 2;

    private static TabItem[] m_HomesFragmentList = new TabItem[]{
            new TabItem(R.id.rb_home_tab_main, R.string.home_tab_main, HomesFragment.instance()),
            new TabItem(R.id.rb_home_tab_area, R.string.home_tab_find, FindFragment.instance()),
            new TabItem(R.id.rb_home_tab_mine, R.string.home_tab_mine, MyFragment.instance()),

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //替换为原来的主题，在onCreate之前调用 ,防止应用启动白屏
        setTheme(R.style.AppTheme);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setImgTransparent(this);
        setImmersiveStatusBar(true);
        scale_to_normal = AnimationUtils.loadAnimation(this, R.anim.scale_to_normal_x_scale);
        initView();
        addListener();
        initData();
    }
    public static void setImgTransparent(Activity activity){
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = activity.getWindow();
            window.clearFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                            | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
//                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION  //不隐藏和透明虚拟导航栏  因为会遮盖底部的布局
                            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE//保持布局状态
            );
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
//            window.setNavigationBarColor(Color.TRANSPARENT);//不隐藏和透明虚拟导航栏  因为会遮盖底部的布局

        }
    }

    protected void setImmersiveStatusBar(boolean fontIconDark) {
        if (fontIconDark) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                setStatusBarFontIconDark(COMMON);
            } else if (OSUtils.isMiui()) {
                setStatusBarFontIconDark(MIUI);
            } else if (OSUtils.isFlyme()) {
                setStatusBarFontIconDark(FLYME);
            } else {//其他情况下我们将状态栏设置为灰色，就不会看不见字体
//                setStatusBarPlaceColor(Color.LTGRAY);//灰色
            }
        }
    }

    /**
     * 设置文字颜色
     */
    public void setStatusBarFontIconDark(int type) {
        switch (type) {
            case MIUI:
                setMiuiUI(true);
                break;
            case COMMON:
                setCommonUI();
                break;
            case FLYME:
                setFlymeUI(true);
                break;
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        if (TextUtils.isEmpty(LoginTool.getToken())) {
            if ( curItem == 2){
                changePage(0);
            }else {
                changePage(curItem);
            }
        }

    }

    @Override
    protected void initView() {
        findViewById(R.id.rb_home_tab_main).setOnClickListener(this);
        findViewById(R.id.rb_home_tab_area).setOnClickListener(this);
        findViewById(R.id.rb_home_tab_mine).setOnClickListener(this);
        tv_home = (TextView) findViewById(R.id.tv_home);
        tv_area = (TextView)findViewById(R.id.tv_area);
        tv_mine = (TextView) findViewById(R.id.tv_mine);

        img_home = (ImageView) findViewById(R.id.img_home);
        img_area = (ImageView)findViewById(R.id.img_area);

        img_mine = (ImageView) findViewById(R.id.img_mine);

        setDefaultChose();
    }
    //设置状态栏高度
    public int getStatusBarHeight() {
        int statusBarHeight = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            statusBarHeight = getResources().getDimensionPixelSize(resourceId);
        }
        return statusBarHeight;
    }

    public void setCommonUI() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

        }
    }

    public void setFlymeUI(boolean dark) {
        try {
            Window window = getWindow();
            WindowManager.LayoutParams lp = window.getAttributes();
            Field darkFlag = WindowManager.LayoutParams.class.getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
            Field meizuFlags = WindowManager.LayoutParams.class.getDeclaredField("meizuFlags");
            darkFlag.setAccessible(true);
            meizuFlags.setAccessible(true);
            int bit = darkFlag.getInt(null);
            int value = meizuFlags.getInt(lp);
            if (dark) {
                value |= bit;
            } else {
                value &= ~bit;
            }
            meizuFlags.setInt(lp, value);
            window.setAttributes(lp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setMiuiUI(boolean dark) {
        try {
            Window window = getWindow();
            Class clazz = getWindow().getClass();
            Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
            Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
            int darkModeFlag = field.getInt(layoutParams);
            Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
            if (dark) {    //状态栏亮色且黑色字体
                extraFlagField.invoke(window, darkModeFlag, darkModeFlag);
            } else {
                extraFlagField.invoke(window, 0, darkModeFlag);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void initData() {
    }

    @Override
    protected void onRestart() {
        super.onRestart();

    }



    @Override
    protected void addListener() {
        CommonListner.instance().setLoginInListeners(new CommonListner.LoginInListener() {
            @Override
            public void ready() {
                changePage(curItem);
            }
        });

        CommonListner.instance().setLoginOutListeners(new CommonListner.LoginOutListener() {
            @Override
            public void ready() {
                changePage(0);
            }
        });

    }
    public void changePage(int page) {
        if (m_HomesFragmentList == null){
            m_HomesFragmentList = new TabItem[]{
                    new TabItem(R.id.rb_home_tab_main, R.string.home_tab_main, HomesFragment.instance()),
                    new TabItem(R.id.rb_home_tab_area, R.string.home_tab_find, FindFragment.instance()),
                    new TabItem(R.id.rb_home_tab_mine, R.string.home_tab_mine, MyFragment.instance()),

            };
        }
        showOrHideFragmentById(m_HomesFragmentList[page].getFragId(), m_HomesFragmentList, R.id.home_fragments);
        switch (page) {
            case 0:
                mainChange();
                break;
            case 1:
                areaChange();
                break;
            case 2:
                mineChange();
                break;

        }

    }

    @Override
    public void onClick(View v) {

        if (v.getId() == R.id.rb_home_tab_mine) {
            if (TextUtils.isEmpty(LoginTool.getToken())) {
                curItem = 2;
                Bundle bundle = new Bundle();
                bundle.putString("from","mine");
                startAct(this, LoginsActivity.class,bundle);
                return;
            }
        }
        if (v.getId() == R.id.rb_home_tab_area) {
            if (TextUtils.isEmpty(LoginTool.getToken())) {
                curItem = 0;
                Bundle bundle = new Bundle();
                bundle.putString("from","mine");
                startAct(this, LoginsActivity.class,bundle);
                return;
            }
        }
        switch (v.getId()) {
            case R.id.rb_home_tab_main:
                curItem = 0;
                mainChange();
                break;
            case R.id.rb_home_tab_area:
                curItem = 1;
                areaChange();
                break;
            case R.id.rb_home_tab_mine:
                curItem = 2;
                mineChange();
                break;
        }
        showOrHideFragmentById(v.getId(), m_HomesFragmentList, R.id.home_fragments);

    }



    private void mainChange() {
        img_home.startAnimation(scale_to_normal);
        tv_home.setTextColor(ContextCompat.getColor(this,R.color.maincolor));
        tv_area.setTextColor(ContextCompat.getColor(this,R.color.unselectcolor));
        tv_mine.setTextColor(ContextCompat.getColor(this,R.color.unselectcolor));
        tv_area.setVisibility(View.VISIBLE);

        int size = DensityUtils.dp2px(22,this);
        img_area.setLayoutParams(new LinearLayout.LayoutParams(size, size));
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(img_area.getLayoutParams());
        lp.setMargins(0, 0, 0, 0);
        img_area.setLayoutParams(lp);
        img_home.setImageResource(R.mipmap.shangquan_sel);
        img_area.setImageResource(R.mipmap.shangcheng);
        img_mine.setImageResource(R.mipmap.wo);
    }


    private void areaChange() {
        img_area.startAnimation(scale_to_normal);
        tv_home.setTextColor(ContextCompat.getColor(this,R.color.unselectcolor));
        tv_area.setTextColor(ContextCompat.getColor(this,R.color.maincolor));
        tv_mine.setTextColor(ContextCompat.getColor(this,R.color.unselectcolor));
        img_home.setImageResource(R.mipmap.shangquan);
        if (!TextUtils.isEmpty(UserInfo.instance().getLogo())){
            ImageLoadUtils.INSTANCE.loadImageView(img_area,MyConfig.IMG_URL+UserInfo.instance().getLogo());
            tv_area.setVisibility(View.GONE);


            int size = DensityUtils.dp2px(45,this);
            img_area.setLayoutParams(new LinearLayout.LayoutParams(size, size));
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(img_area.getLayoutParams());
            lp.setMargins(0, 0, 0, 10);
            img_area.setLayoutParams(lp);
        }
//        img_area.setImageResource(R.mipmap.shangcheng_sel);
        img_mine.setImageResource(R.mipmap.wo);
    }

    private void mineChange() {
        img_mine.startAnimation(scale_to_normal);
        tv_area.setVisibility(View.VISIBLE);

        int size = DensityUtils.dp2px(22,this);
        img_area.setLayoutParams(new LinearLayout.LayoutParams(size, size));
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(img_area.getLayoutParams());
        lp.setMargins(0, 0, 0, 0);
        img_area.setLayoutParams(lp);
        tv_home.setTextColor(ContextCompat.getColor(this,R.color.unselectcolor));
        tv_area.setTextColor(ContextCompat.getColor(this,R.color.unselectcolor));
        tv_mine.setTextColor(ContextCompat.getColor(this,R.color.maincolor));
        img_home.setImageResource(R.mipmap.shangquan);
        img_area.setImageResource(R.mipmap.shangcheng);
        img_mine.setImageResource(R.mipmap.wo_sel);
    }

    private void setDefaultChose() {
        showOrHideFragmentById(R.id.rb_home_tab_main, m_HomesFragmentList, R.id.home_fragments);
        tv_home.setTextColor(ContextCompat.getColor(this,R.color.maincolor));
        img_home.setImageResource(R.mipmap.shangquan_sel);

    }

    private void showOrHideFragmentById(int checkedId, TabItem[] list, int fragmentLayoutId) {

        for (int i = 0; i < list.length; i++) {
            Fragment fragment = list[i].getFragment();
            int fragId = list[i].getFragId();
            int titleResId = list[i].getFragName();
            if (fragId == checkedId) {
                showFragmentById(fragment, fragmentLayoutId, fragId + "");
            } else {
                hideFragment(fragment);
            }
        }
    }





    /**
     * 请求CAMERA权限码
     */
    public static final int REQUEST_CAMERA_PERM = 101;

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            if (requestCode == REQUEST_CAMERA_PERM){
                PermissionUtil.openPermissionDialog(this,"智慧养车需要申请camera权限,请打开设置页面去申请");

            }


        }
    }

    /**
     * EsayPermissions接管权限处理逻辑
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == WRITE_EXTERNAL_STORAGE_REQUEST_CODE) {

        }else{
            // Forward results to EasyPermissions
            EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
        }

    }



    private long firstTime = 0;

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                long secondTime = System.currentTimeMillis();
                if (secondTime - firstTime > 2000) {                                         //如果两次按键时间间隔大于2秒，则不退出
                    Toast.makeText(this, "再按一次可以退出智慧养车", Toast.LENGTH_SHORT).show();
                    firstTime = secondTime;//更新firstTime
                    return true;
                } else {                                                    //两次按键小于2秒时，退出应用
                    System.exit(0);
                }
                break;
        }
        return super.onKeyUp(keyCode, event);
    }



}
